/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wf3.hibernate;

import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;

/**
 *
 * @author romulogalindo
 */
public class WQuery {

    Query mquery;
    String query;
    long time = 0L;

    public WQuery(Query mquery) {
        this.mquery = mquery;
        query = mquery.getQueryString();
    }

    public List list() throws HibernateException {
        time = System.currentTimeMillis();
        List l = mquery.list();
        time = System.currentTimeMillis() - time;
        return l;
    }

    public Object uniqueResult()  throws HibernateException {
        time = System.currentTimeMillis();
        Object o = mquery.uniqueResult();
        time = System.currentTimeMillis() - time;
        return o;
    }

    public Query getMquery() {
        return mquery;
    }

    public void setMquery(Query mquery) {
        this.mquery = mquery;
    }

    public Query setInteger(String name, int i) {
        query = query.replace(":" + name, "" + i);
        return mquery.setInteger(name, i);
    }

    public Query setString(String name, String v) {
        try {
            query = query.replace(":" + name, "\'" + v + "\'");
        } catch (Exception ep) {
            query = query.replaceAll(":" + name, "\'?\'");
        }
        return mquery.setString(name, v);
    }

    public Query setLong(String name, long l) {
        query = query.replace(":" + name, "" + l);
        return mquery.setLong(name, l);
    }

    public Query setShort(String name, short s) {
        query = query.replace(":" + name, "" + s + "::smallint");
        return mquery.setShort(name, s);
    }

    public Query setDate(String name, Date t) {
        query = query.replace(":" + name, "" + t);
        return mquery.setDate(name, t);
    }

    public Query setTime(String name, Date t) {
        query = query.replace(":" + name, "" + t);
        return mquery.setTime(name, t);
    }

    public Query setTimestamp(String name, Date t) {
        query = query.replace(":" + name, "" + t);
        return mquery.setTimestamp(name, t);
    }

    public Query setShort(String name, Short s) {
        query = query.replace(":" + name, "" + s + "::smallint");
        return mquery.setShort(name, s);
    }

    /**
     * Consigue la query ejecutada incluyendo el timpo que demoro en ejecutarse
     *
     */
    public String SQLQuery() {
        return "[" + time + " ms]" + query;
    }
}